// pages/detail/detail.js
import {
  getDetail, 
  getRecommends, 
  GoodsBaseInfo,
  ShopInfo,
  ParamInfo
} from '../../service/detail.js'
import {BACK_TOP_POSITION} from '../../common/const.js'
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    iid: '', // 1m7c6iu
    topImages: [],
    baseInfo: {},
    shopInfo: {},
    detailInfo: {},
    paramInfo: {},
    commentInfo: {},
    recommends: {},
    showBackTop: false,
    topPosition: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      iid: options.iid
    })
    this._getDetail(this.data.iid)
    this._getRecommends()
  },
  onBackTop(){
    this.setData({
      showBackTop: false,
      topPosition: 0
    })
  },
  scrollPosition(e){
    const position = e.detail.scrollTop
    this.setData({
      showBackTop: position > BACK_TOP_POSITION
    })
  },

  addCart(){
    //1.获取商品对象
    const obj = {}
    obj.iid = this.data.iid
    obj.imageURL = this.data.topImages[0] 
    obj.title = this.data.baseInfo.title
    obj.desc = this.data.baseInfo.desc
    obj.price = this.data.baseInfo.realPrice

    //2.加入到购物车
    app.addToCart(obj)
    //3.提示加入购物车成功
    wx.showToast({
      title: '加入购物车成功',
    })
  },
  _getDetail(iid){
    getDetail(iid).then(res => {
      console.log(res)
      const data = res.result
      //1.取出顶部图片
      const topImages = data.itemInfo.topImages
      //2.创建BaseInfo对象
      const baseInfo = new GoodsBaseInfo(data.itemInfo, data.columns, data.shopInfo.services)
      //3.创建ShopInfo对象
      const shopInfo = new ShopInfo(data.shopInfo)
      //4.获取detailInfo信息
      const detailInfo = data.detailInfo
      //5.创建ParamInfo对象
      const paramInfo = new ParamInfo(data.itemParams.info, data.itemParams.rule)
      //6.获取评论信息
      let commentInfo = {}
      if(data.rate && data.rate.cRate > 0){
        commentInfo = data.rate.list[0]
      }
      this.setData({
        topImages,
        baseInfo,
        shopInfo,
        detailInfo,
        paramInfo,
        commentInfo
      })
    })
  },
  _getRecommends(){
    getRecommends().then(res => {
      this.setData({
        recommends: res.data.list
      })
    })
  }
})